package com.m1book.site;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.m1book.domain.BookNotExistException;
import com.m1book.domain.M1BookService;
import com.m1book.domain.book.Book;

@Controller
@SessionAttributes({"currentUser", "book", "bookInfo"})
public class BookSearchController {
	private static final Logger logger = LoggerFactory.getLogger(BookSearchController.class);
	
	@Autowired
	private M1BookService m1bookService;
	
	@RequestMapping(value = "/search", method = RequestMethod.GET)
	public String search() {
		return "search";
	}
	
	@RequestMapping(value = "/searchby", method = RequestMethod.GET)
	public String searchResult(@RequestParam(required = true, value = "isbn") String isbn, @RequestParam(required = false, value = "t") String t, Model model) {
		model.addAttribute("isbn", isbn);
		String result = "bookinfo";
		if (t != null && t.equalsIgnoreCase("true")) {
			result = "tbookinfo";
		}
		
		boolean found = true;
		try {
			Book book = m1bookService.searchBookByISBNFromLocal(isbn);
			model.addAttribute("bookInfo", book.getDoubanBookInfo());
			model.addAttribute("book", book);
			logger.info("found book by isbn: " + isbn + " from local.");
		} catch (BookNotExistException e) {
			found = false;
			logger.info("not found book by isbn: " + isbn + " from local.");
		}
		
		if (!found) {
			try {
				Book book = m1bookService.searchBookByISBNFromDouban(isbn);
				model.addAttribute("bookInfo", book.getDoubanBookInfo());
				logger.info("found book by isbn: " + isbn + " from douban.");
			} catch (BookNotExistException e) {
				logger.info("not found book by isbn: " + isbn + " from douban.");
				result = "booknotfound";
			}
		}
		
		return result;
	}

}
